<?php
/**
 * 图片上传控制器
 * User: Administrator
 * Date: 2017/3/13
 * Time: 17:43
 */
namespace app\backend\controller;

use think\Controller;

class ImageUploadController extends Controller
{
    private $_memberId  = null;
    private $_imageConf = null;
    public function __construct()
    {
        parent::__construct();
        $this->_memberId = $this->isLogin();
        $this->_imageConf = load_config('type', 'image');
    }

    /**
     * 图片上传
     * @return [type] [description]
     */
    public function upload()
    {
        $nArr = ['action','tt','callback','limit','offset','id'];
        foreach ($_REQUEST as $k=>$v) {
            if ((!is_array($v))&&(!is_object($v))) {
                if (in_array($k, $nArr)) {
                    $nInfo[$k]=$v;
                }
            }
        }

        if (!$nInfo) {
            $this->apiReturn(400, [], '参数缺失');
        }
        $nInfo['tt'] = trim($nInfo['tt']);
        if ($_FILES[$nInfo['tt']]['size']>0) {
            include '/var/www/html/zft/application/backend/Uploader.php';
            if (in_array($nInfo['tt'], $this->_imageConf)) {
                $dirname = $nInfo['tt']. '/'. $_SESSION['username'];
                $config  = array(
                    'simpleFolder'  => true,
                    "savePath"      => IMAGE_UPLOAD_DIR . "{$dirname}",
                    "maxSize"       => 2048, //单位KB
                    "allowFiles"    => array(".gif", ".png", ".jpg", ".jpeg", ".bmp"),
                );
                $up   = new \Uploader($nInfo['tt'], $config);
                $res = $up->upFile();
                if ($res['code'] != 200) {
                    $json = "{\"status\":\"fail\", \"key\":\"".$res['msg']."\"}";
                    echo '<script>window.parent.' . $nInfo['callback'] . '('.$json.');</script>';
                    die;
                    //$this->apiReturn($res['code'], [], $res['msg']);
                }

                $info = $up->getFileInfo();
                if ($info['state']=='SUCCESS') {
                    if (isset($_REQUEST["dname"]) && $nInfo['id']==$_SESSION['memberID']) {
                        $_SESSION['dname']=$_REQUEST["dname"];
                    }
                    $json = '{"status":"ok", "key":"'.str_replace(IMAGE_REMOVE_DIR, IMAGE_URL, $info['url']).'"}';
                } else {
                    $json = '{"status":"fail", "key":"上传失败"}';
                }
                echo '<script>window.parent.' . $nInfo['callback'] . '('.$json.');</script>';
            } else {
                $msg = '图片类型有误';
                $json = "{\"status\":\"fail\", \"key\":\"".$msg."\"}";
                echo '<script>window.parent.' . $nInfo['callback'] . '('.$json.');</script>';
                die;
            }
        }
    }
}